package com.example.musicplayer.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.example.musicplayer.R
import com.example.musicplayer.model.RecommendMusic

/**
 * 推荐音乐适配器
 */
class RecommendMusicAdapter(
    private val context: Context,
    private val recommendMusicList: List<RecommendMusic>,
    private val listener: OnItemClickListener?
) : BaseAdapter() {
    private val inflater: LayoutInflater = LayoutInflater.from(context)

    interface OnItemClickListener {
        fun onItemClick(recommendMusic: RecommendMusic?)
    }

    override fun getCount(): Int {
        return recommendMusicList.size
    }

    override fun getItem(position: Int): Any {
        return recommendMusicList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.grid_item, parent, false)
        }

        val imageView = convertView?.findViewById<ImageView>(R.id.grid_item_image)
        val textView = convertView?.findViewById<TextView>(R.id.grid_item_text)
        val recommendMusic = recommendMusicList[position]

        Glide.with(context)
            .load(recommendMusic.recImgUrl)
            .placeholder(R.drawable.ic_launcher_background)
            .error(R.drawable.ic_launcher_background)
            .into(imageView!!)

        textView?.text = recommendMusic.name

        convertView?.setOnClickListener { listener?.onItemClick(recommendMusic) }

        return convertView!!
    }

}